package com.java.onlineshop.impl;

import com.java.onlineshop.dao.IUserDao;
import com.java.onlineshop.pojo.Country;
import com.java.onlineshop.pojo.Province;
import com.java.onlineshop.pojo.User;
import com.java.onlineshop.pojo.Userinfo;
import com.java.onlineshop.service.ICountryService;
import com.java.onlineshop.service.IProvinceService;
import com.java.onlineshop.service.impl.CountryServiceImpl;
import com.java.onlineshop.service.impl.ProvinceServiceImpl;
import com.java.onlineshop.util.BasicDao;
import com.java.onlineshop.util.JdbcUtil;

import java.sql.*;
import java.util.List;

/**
 * @program: onlineshop
 * @description: IUserDao的实现类
 * @author: ShuangChenYue
 * @create: 2021-05-28 13:31
 **/
public class UserDaoImpl implements IUserDao
{

    @Override
    public List<Country> findAllCountry()
    {
        return BasicDao.getObjectToList(Country.class,"select * from country");
    }

    @Override
    public List<Province> findAllProvince()
    {
        return BasicDao.getObjectToList(Province.class,"select * from province");
    }
//=======================================================用户注册========================================================
    @Override
    public void addUser(User user)
    {
        System.out.println("进入注册用户方法");
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try
        {
            //1.获取连接
            connection = JdbcUtil.getConnection();
            //2.设置手动提交
            connection.setAutoCommit(false);
            //3.预编译sql语句
            String sql = "insert into user(name,password) values(?,?)";
            preparedStatement = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
            //4.填充占位符
            System.out.println("进入填充占位符步骤");
            preparedStatement.setString(1, user.getName());
            preparedStatement.setString(2, user.getPassword());
            //5.执行此次操作
            System.out.println("进入执行操作前");
            int i = preparedStatement.executeUpdate();
            System.out.println(i+"条记录被影响");
            //6.得到用户的主键
            resultSet = preparedStatement.getGeneratedKeys();
            int key=0;
            while (resultSet.next())
            {
                key = resultSet.getInt(1);
            }
            //7.将本次操作的ps关掉
            JdbcUtil.relase(preparedStatement);

            //8.给userinfo表插入数据
            Userinfo userinfo = new Userinfo();
            //9.得到国家和省份
            int countryid = user.getUserinfo().getCountry().getId();
            int provinceid = user.getUserinfo().getProvince().getId();
            //9.预编译sql语句
            String infosql = "insert into userinfo(id,email,phone,city,countryid,provinceid,addressdetail) values(?,?,?,?,?,?,?)";
            preparedStatement = connection.prepareStatement(infosql);
            //10.填充占位符
            preparedStatement.setInt(1,key);
            preparedStatement.setString(2,user.getUserinfo().getEmail());
            preparedStatement.setString(3,user.getUserinfo().getPhone());
            preparedStatement.setString(4,user.getUserinfo().getCity());
            preparedStatement.setInt(5,countryid);
            preparedStatement.setInt(6,provinceid);
            preparedStatement.setString(7,user.getUserinfo().getAddressdetail());
            int j = preparedStatement.executeUpdate();
            System.out.println(j+"条记录被影响");
            //11.手动提交
            connection.commit();
        }catch (Exception e){
            e.printStackTrace();
        }finally
        {
            JdbcUtil.relase(resultSet,preparedStatement,connection);
        }
    }
//=======================================================用户登录========================================================
    @Override
    public User findUserByNameAndPassword(String name, String password)
    {
        ICountryService countryService = new CountryServiceImpl();
        IProvinceService provinceService = new ProvinceServiceImpl();
        //首先查找用户所有信息并返回
        User user = BasicDao.getObject(User.class, "select id,name,password from user where name=? and password=?", name, password);
        //此时返回了一个user，里面有id，但并没有info的信息，于是需要得到该id所对应的info
        int id = user.getId();
        //用此id去info表中查找所对应的info，便要用到最原始的JDBC
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        Userinfo userinfo = null;
        try
        {
            //1.获取连接
            connection = JdbcUtil.getConnection();
            //2.关闭自动提交，设置手动提交
            connection.setAutoCommit(false);
            //3.预编译sql语句
            String sql = "select * from userinfo where id=?";
            preparedStatement = connection.prepareStatement(sql);
            //4.填充占位符
            preparedStatement.setInt(1,id);
            //5.执行操作并返回结果集
            resultSet = preparedStatement.executeQuery();
            //6.处理结果集
            if (resultSet.next())
            {
                //7.若结果集中有数据，则将结果集中的数据给存到info对象中
                userinfo = new Userinfo();
                userinfo.setId(id);
                userinfo.setEmail(resultSet.getString("email"));
                userinfo.setPhone(resultSet.getString("phone"));
                userinfo.setCity(resultSet.getString("city"));
                //由于userinfo中保存的国家和省份是对象，所以要先得到id，再用id去查找到对象，再将查出来的对象保存进info中
                int countryid = resultSet.getInt("countryid");
                //调用根据id查国家的方法
                Country country = countryService.findCountryById(countryid);
                //再将country的id设置成从info表中查到的id
                country.setId(countryid);
                //province也认识同样的操作
                int provinceid = resultSet.getInt("provinceid");
                Province province = provinceService.findProvinceById(provinceid);
                province.setId(provinceid);
                userinfo.setCountry(country);
                userinfo.setProvince(province);
                userinfo.setAddressdetail(resultSet.getString("addressdetail"));
                userinfo.setUser(user);
                user.setUserinfo(userinfo);
            }
            connection.commit();
        }catch (Exception e)
        {
            try
            {
                connection.rollback();
            } catch (SQLException throwables)
            {
                throwables.printStackTrace();
            }
            e.printStackTrace();
        }finally
        {
            JdbcUtil.relase(resultSet,preparedStatement,connection);
        }

        return user;
    }

    @Override
    public void updateUser(User user) throws SQLException
    {
        System.out.println("进入修改具体方法");
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try
        {
            //1.获取连接
            connection = JdbcUtil.getConnection();
            //2.关闭自动提交，设置手动提交
            connection.setAutoCommit(false);
            //3.预编译sql语句
            String sql = "update user set name=?,password=? where id=?";
            preparedStatement = connection.prepareStatement(sql);
            //4.填充占位符
            preparedStatement.setString(1, user.getName());
            preparedStatement.setString(2, user.getPassword());
            preparedStatement.setInt(3,user.getId());
            int i = preparedStatement.executeUpdate();
            System.out.println(i+"条记录被影响");
            JdbcUtil.relase(preparedStatement);
            //预编译sql语句
            String infosql = "update userinfo set email=?,phone=?,city=?,countryid=?,provinceid=?,addressdetail=? where id=?";
            preparedStatement = connection.prepareStatement(infosql);
            //填充占位符
            Userinfo userinfo = user.getUserinfo();
            preparedStatement.setString(1,userinfo.getEmail());
            preparedStatement.setString(2,userinfo.getPhone());
            preparedStatement.setString(3,userinfo.getCity());
            preparedStatement.setInt(4,userinfo.getCountry().getId());
            preparedStatement.setInt(5,userinfo.getProvince().getId());
            preparedStatement.setString(6,userinfo.getAddressdetail());
            preparedStatement.setInt(7,userinfo.getId());
            int j = preparedStatement.executeUpdate();
            System.out.println(j+"条记录被影响");
            connection.commit();
            System.out.println("已全部提交");
        }catch (Exception e)
        {
            connection.rollback();
            e.printStackTrace();
        }finally
        {
            JdbcUtil.relase(connection);
        }
    }

}
